import apis from '@/apis'
import { apiPromise } from '@/helper/uniPromise'
import { getUserInfo, setUserInfo, clearUserInfo } from '@/helper/loginManage'

export default {
  namespaced: true,
	state: {
		loginCode: '',
		loginPopup: false,
		isValidloginState: false,
		userInfo: getUserInfo(),
		balanceInfo: {}
	},
	mutations: {
		setData (state, { key, value }) {
			state[key] = value
		}
	},
	actions: {
		/**
		 * 回收宝、微信、支付宝登录
		 */
		async login ({ dispatch }, params) {
			// #ifdef MP-WEIXIN || MP-ALIPAY
			const [authRes] = await apiPromise('login', {
				onlyAuthorize: true
			})
			if (authRes.code) {
				params.code = authRes.code
			} else {
				return [{ _errStr: '获取登录凭证失败' }, null]
			}
			// #endif
			// #ifdef MP-ALIPAY
			const [res, err] = await apis.alipayLogin(params)
			// #endif
			// #ifndef MP-ALIPAY
			const [res, err] = await apis.login(params)
			// #endif
			if (res._errCode === '0') {
				dispatch('setUserInfo', res._data || {})
			}
			return [res, err]
		},
		/**
		 * 微信、支付宝登录
		 */
		async getLoginCode ({ commit }) {
			const [res] = await apiPromise('login', {
				onlyAuthorize: true
			})
			const code = res.code || ''
			commit('setData', { key: 'loginCode', value: code })
			return code
		},
		/**
		 * 检查登录状态
		 */
		async checkLoginStatus ({ state, dispatch }) {
			const [res, err] = await apis.checkLoginStatus()
			dispatch('setLoginState', Number(res._data?.status) === 1)
			return [res, err]
		},
		/**
		 * 刷新登录态
		 */
		async refreshLoginStatus ({ state, dispatch }) {
			await dispatch('checkLoginStatus')
			if (!state.isValidloginState) {
				dispatch('login')
			}
		},
		/**
		 * 获取用户信息
		 */
		async getUserInfo ({ state, dispatch }) {
			const [res] = await apis.getUserInfo()
			if (res._errCode === '0') {
				dispatch('setUserInfo', res._data || {})
			}
		},
		/**
		 * 获取用户资产
		 */
		async getBalanceInfo ({ commit }) {
			const [res] = await apis.getBalanceInfo()
			if (res._errCode === '0') {
				commit('setData', { key: 'balanceInfo', value: res._data || {} })
			}
		},
		/**
		 * 更新用户信息
		 */
		setUserInfo ({ state, dispatch, commit }, userInfo) {
			const userData = Object.assign({}, state.userInfo, userInfo)
			commit('setData', { key: 'userInfo', value: userData })
			dispatch('setLoginState', true)
			setUserInfo(userData)
		},
		/**
		 * 更新登录状态
		 */
		setLoginState ({ commit }, status) {
			commit('setData', { key: 'isValidloginState', value: status })
		},
		/**
		 * 退出登录
		 */
		logout ({ dispatch, commit }) {
			commit('setData', { key: 'userInfo', value: {} })
			dispatch('setLoginState', false)
			clearUserInfo()
		}
	}
}